package thread;

import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

public class LogWriter {
    private final BlockingQueue<String> queue;
    private final LoggerThread logger;
    private static final int CAPACITY = 1000;
    public LogWriter(Writer writer){
        // 全局唯一队列，唯一的LoggerThread线程
        this.queue=new LinkedBlockingDeque<>(CAPACITY);
        this.logger=new LoggerThread(writer);
    }

    public void start(){
        logger.start();
    }

    public void log(String msg) throws  InterruptedException{
        queue.put(msg);
    }

    private class LoggerThread extends Thread {
        private final PrintWriter printWriter;

        public LoggerThread(Writer writer) {
            this.printWriter = new PrintWriter(writer, true);

        }

        public void run() {
            try {

                while (true) {
                    printWriter.println(queue.take());
                }
            } catch (InterruptedException ignored) {
                ignored.printStackTrace();
            } finally {
                printWriter.close();
            }
        }
    }

}
